package com.magictower.primary.engine;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Debug;

import com.magictower.primary.R;
import com.magictower.primary.bean.TaskInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @author kejunzhan
 * @since 2017/12/20
 */

public class TaskInfoParser {
    public static List<TaskInfo> getTaskInfos(Context context) {
        List<TaskInfo> infos = new ArrayList<>();
        TaskInfo info;
        //获取包管理器
        PackageManager pm = context.getPackageManager();
        //获取当前活动管理器
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        //获取当前运行的进程
        List<RunningAppProcessInfo> appProcesses = am.getRunningAppProcesses();
        for (RunningAppProcessInfo process : appProcesses) {
            info = new TaskInfo();
            String processName = process.processName;
            info.setPackageName(processName);

            /*
            获取程序所占内存
             */
            Debug.MemoryInfo[] memoryInfos = am.getProcessMemoryInfo(new int[]{process.pid});
            //获取总共弄脏了多少内存，即占有多少内存
            long totalMemory = memoryInfos[0].getTotalPrivateDirty()*1024;
            info.setMemorySize(totalMemory);
            try {
                PackageInfo packageInfo = pm.getPackageInfo(processName, 0);
                /*
                1.获取应用名字
                2.获取应用icon
                3.判断是否是用户应用/系统应用
                 */
                Drawable drawable = packageInfo.applicationInfo.loadIcon(pm);
                info.setIcon(drawable);
                String appName = packageInfo.applicationInfo.loadLabel(pm).toString();
                info.setAppName(appName);
                int flags = packageInfo.applicationInfo.flags;
                if ((flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                    //系统应用
                    info.setUserApp(false);
                } else {
                    //用户应用
                    info.setUserApp(true);
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
                //有些系统应用没有ICON，设置默认值
                info.setUserApp(false);
                info.setAppName(processName);
                info.setIcon(context.getResources().getDrawable(R.mipmap.ic_launcher));
            }
            infos.add(info);
        }
        return infos;
    }
}
